﻿package src.com.online.rpg.timer 
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.getTimer;
	import flash.utils.Timer;
	
	/*
	 * Timer Comparison
	 * 
	 * This example compares timing using the flash.utils.Timer class and flash.utils.getTimer function.
	 * We show examples of using both methods to tick separate clocks at 30Hz.
	 * After a bit of time, you should notice that there is an increasing difference between the two methods.
	 * In fact, Timer seems to tick faster than real time in this case.
	 * The AS3 docs state: " Depending on the SWF file's framerate or Flash Player's environment 
	 * (available memory and other factors), Flash Player or Adobe AIR may dispatch events at slightly offset intervals."
	 * Therefore, you should use getTimer for all game-related timing and updating.
	 */
	public class TimerComparison extends Sprite
	{
		private const GAME_FRAMERATE:Number		= 30;
		
		private var _timer:Timer;
		private var _time:uint;
		private var _clockExample1:ClockExample;
		private var _clockExample2:ClockExample;
		
		public function TimerComparison() 
		{
			// Method 1: Timer
			_timer = new Timer(GAME_FRAMERATE);
			_timer.addEventListener(TimerEvent.TIMER, onTimer);
			
			// Method 2: getTimer every enterFrame
			addEventListener(Event.ENTER_FRAME, onEnterFrame);
			
			_clockExample1 = new ClockExample();
			addChild(_clockExample1);
			
			_clockExample2 = new ClockExample();
			_clockExample2.y = 200;
			addChild(_clockExample2);
			
			_time = getTimer();
			_timer.start();
		}
		
		// ClockExample1 uses flash.utils.Timer		
		private function onTimer(e:TimerEvent):void
		{
			// the timer runs GAME_FRAMERATE times per second,
			// therefore each tick should be 1 / GAME_FRAMERATE seconds apart
			_clockExample1.update(1 / GAME_FRAMERATE);
		}
		
		// ClockExample2 uses flash.utils.getTimer
		private function onEnterFrame(e:Event):void
		{
			// calculate how much time has passed (dt) since we last received this event
			var newTime:uint = getTimer();
			var dt:uint = newTime - _time;	// change in time = the current time - the previous time
			_time = newTime;
			
			// update based on how much time has passed
			_clockExample2.update(dt/1000); // dt is in ms, so we /1000 to turn into seconds
		}
	}

}